import random
import re
from datetime import datetime

from flask import request, abort, current_app, make_response, jsonify, session
from info import redis_store

from info import db
from info.models import User
from utils.response_code import RET
import constants
from . import passport_blu
from info.utils.captcha.captcha import captcha
from yuntongxun.sms import CCP


# TODO 短信生成
@passport_blu.route('/sms_code', methods=['POST'])
def send_sms_code():
    # 手机号码的获取以及图片验证码内容
    #     params_dict = json.loads(request.data)

    params_dict = request.json
    print(type(params_dict))
    mobile = params_dict.get('mobile')
    image_code = params_dict.get('image_code')
    image_code_id = params_dict.get('image_code_id')
    if not all([mobile, image_code_id, image_code]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if not re.match(r"1[356]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号有误")
    try:
        real_image_code = redis_store.get('ImageCode_' + image_code_id)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="无数据")
    if image_code.upper() != real_image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")
    mobile_str = "%06d" % random.randint(0, 999999)
    current_app.logger.debug(mobile_str)
    # result = CCP().send_template_sms(mobile, [mobile_str, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送失败")
    try:
        redis_store.set('sms' + mobile, mobile_str)
    except Exception as e:
        return jsonify(errno=RET.SERVERERR, errmsg="数据库出错")
    return jsonify(errno=RET.OK, errmsg="验证成功")


# TODO 生成验证码
@passport_blu.route('/image_code')
def get_image_code():
    print("------------")
    image_code_id = request.args.get('imageCodeId', None)
    if not image_code_id:
        return abort(403)

    name, text, image = captcha.generate_captcha()
    # 保存验证码文字内容到redis
    try:
        redis_store.set('ImageCode_' + image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)

    # 5.返回图片验证
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response


# TODO 表单提交
@passport_blu.route('/register', methods=['POST'])
def register():
    param_dict = request.json
    mobile = param_dict.get('mobile')
    smscode = param_dict.get('smscode')
    password = param_dict.get('password')
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if not re.match(r"1[356]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号有误")
    try:
        real_sms_code = redis_store.get('sms' + mobile)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="无数据")

    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg="短信错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    # 记录最后一次登陆是时间
    user.last_login = datetime.now()
    # TODO 密码处理
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据报错失败")
    # session储存的目的是服务器验证用户登陆
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    return jsonify(errno=RET.OK, errmsg="验证成功")
    # TODO 重新开始写
    # param_dict = request.json
    # mobile = param_dict.get('mobile',None)
    # smscode = param_dict.get('smscode',None)
    # password = param_dict.get('password',None)
    # if not all([mobile,smscode,password]):
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # if not re.match(r"1[345678]",mobile):
    #     return jsonify(errno=RET.PARAMERR, errmsg="手机号不合法")
    # try:
    #     real_sms_code = redis_store.get('sms' + mobile)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.PARAMERR, errmsg="数据库错误")
    # if not real_sms_code:
    #     return jsonify(errno=RET.PARAMERR, errmsg="验证码过期")
    # if real_sms_code != smscode:
    #     return jsonify(errno=RET.PARAMERR, errmsg="短信验证错误")
    # user = User()
    # user.mobile = mobile
    # user.nick_name = mobile
    # user.password = password
    # try:
    #     db.session.add(user)
    #     db.session.commit()
    # except Exception as e :
    #     current_app.logger.error(e)
    #     db.session.rollback()
    #     return jsonify(errno=RET.PARAMERR, errmsg="数据库错误")
    # session['user_id'] = user.id
    # session['nick_name'] = user.nick_name
    # session['mobile'] = mobile
    # return jsonify(errno=RET.OK, errmsg="验证成功")

@passport_blu.route('/login',methods=["POST"])
def login():
    # param_dict = request.json
    # mobile = param_dict.get('mobile')
    # password = param_dict.get('password')
    # if not all([mobile, password]):
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # if not re.match(r"1[356]\d{9}", mobile):
    #     return jsonify(errno=RET.PARAMERR, errmsg="手机号有误")
    # try:
    #     user = User.query.filter(User.mobile==mobile).first()
    # except Exception as e :
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    # if not user :
    #     return jsonify(errno=RET.NODATA, errmsg="手机号不村在")
    # if not user.check_passowrd(password):
    #     return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    # #  session 的目的是保存登陆状态，将用户的信息存储在session中
    # session['user_id'] = user.id
    # session['mobile'] = user.mobile
    # session['nick_name'] = user.nick_name
    # # 设置最后一次登陆
    # user.last_login =datetime.now()
    #
    #
    # return jsonify(errno=RET.OK, errmsg="验证成功")
    param_dict = request.json
    mobile = param_dict.get('mobile',None)
    password = param_dict.get('password',None)
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if not re.match(r"1[34578]",mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码有误")
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不错在")
    if not user.check_passowrd(password):
        return jsonify(errno=RET.PARAMERR, errmsg="密码错误")
    session['user_id'] = user.id
    session['mobile'] = mobile
    session['nick_name'] = user.nick_name
    user.last_login = datetime.now()
    return jsonify(errno=RET.OK, errmsg="验证成功")


@passport_blu.route('/logout')
def logout():
    session.pop("user_id",None)
    session.pop("mobile",None)
    session.pop("nick_name",None)
    return jsonify(errno=RET.OK, errmsg="删除成功")

